import React, { useState } from "react";
import { Button, Space, message } from "antd";
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { lineBatchTypes, modalPropsType  } from "@/constants/types";
import { useModel } from "@umijs/max";
import { useRequest } from 'ahooks';
import { arrayConvertToObj, calculateTableWidth } from "@/utils/util";
import { fetchServiceProviderOptions, fetchSettlementWeeksByYear } from "@/pages/BasicInfo/services";
import { fetchLpsLineBatchList, addLpsLineBatch, updateLpsLineBatch } from "../services";
import LineBatchUpdate from "../modals/LineBatchUpdate";
import { useComponentDidMount } from "@/hooks";

const LineBatch = () => {
  // dict
  const {getDict} = useModel('dictModel');
  const years = arrayConvertToObj(getDict('year'));
  const countrys = arrayConvertToObj(getDict('country'));
  const prdList = arrayConvertToObj(getDict('prdType'));
  const sportList = arrayConvertToObj(getDict('sport'));
  const dportList = arrayConvertToObj(getDict('dport'));
  const { settlementWeek } = useModel('settlementWeekModel');
  const {currentWeek, currentYear} = settlementWeek || {};
  const initValues = {year: currentYear || String(new Date().getFullYear()), week: currentWeek};
  
  const [currentRow, setCurrentRow] = useState<lineBatchTypes | null>(null);

  const [weeks, setWeeks] = useState({});

  // lineBatch
  const [visible, setVisible] = useState<boolean>(false);
  const {loading: addLineBatchLoading, runAsync: addLineBatchApi} = useRequest(addLpsLineBatch, {manual: true});
  const {loading: updateLineBatchLoading, runAsync: updateLineBatchApi} = useRequest(updateLpsLineBatch, {manual: true});

  const lineBatchProps: modalPropsType = {
    title: currentRow ? '修改船期' : '添加船期',
    visible,
    currentRow,
    loading: addLineBatchLoading || updateLineBatchLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: lineBatchTypes) => {
      const apiFunc = currentRow ? updateLineBatchApi : addLineBatchApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setVisible(false);
        setCurrentRow(null);
      }
    }
  }

  const handleEdit = (record: lineBatchTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }

  const columns: ProColumnType<lineBatchTypes> [] = [
    {
      title: '年份',
      dataIndex: 'year',
      initialValue: initValues.year,
      hideInTable: true,
      valueEnum: years,
      fieldProps: {
        onChange: (year: string) => {
          fetchSettlementWeeksByYear({year}).then(
            res => {
              if (!res?.length) {
                setWeeks({});
              } else {
                setWeeks((res || [])?.reduce((p: any, v: string) => ({...p, [v]: v}), {})) 
              }
            }
          )
        }
      }
    },
    {
      title: '周次',
      dataIndex: 'week',
      hideInTable: true,
      initialValue: initValues.week,
      valueEnum: weeks
      // request: async (params) => {
      //   if (!params?.year) {
      //     return [];
      //   }
      //   debugger;
      //   const { year } = params;
      //   // 异步请求获取月份数据
      //   const weekData = await fetchSettlementWeeksByYear({year});
      //   return weekData.map((week: string) => ({
      //     label: week,
      //     value: week,
      //   }));
      // }
    },
    {
      title: '国家',
      dataIndex: 'country',
      hideInTable: true,
      valueEnum: countrys
    },
    {
      title: '起运港',
      dataIndex: 'sportCode',
      hideInTable: true,
      valueEnum: sportList
    },
    {
      title: '目的港',
      dataIndex: 'dportCode',
      hideInTable: true,
      valueEnum: dportList
    },
    {
      title: '船司',
      dataIndex: 'shipCode',
      hideInTable: true,
      request: async () => {
        const res = await fetchServiceProviderOptions({type: 'ship'});
        return (res || []).map((v: {name: string, code: string}) => ({label: v?.name, value: v?.code}));
      }
    },
    {
      title: '产品',
      dataIndex: 'product',
      hideInTable: true,
      valueEnum: prdList
    },
    {
      title: '年份',
      search: false,
      dataIndex: 'year',
      width: 100
    },
    {
      title: '周次',
      search: false,
      dataIndex: 'week',
      width: 100
    },
    {
      title: '国家',
      search: false,
      dataIndex: 'countryName',
      width: 100
    },
    {
      title: '产品名称',
      search: false,
      dataIndex: 'productName',
      width: 100
    },
    {
      title: '起始地',
      search: false,
      dataIndex: 'sportName',
      width: 120
    },
    {
      title: '目的港',
      search: false,
      dataIndex: 'dportName',
      width: 120
    },
    {
      title: '船司',
      search: false,
      dataIndex: 'shipNames',
      ellipsis: true,
      width: 180
    },
    {
      title: '收货仓库',
      search: false,
      dataIndex: 'cwhNames',
      ellipsis: true,
      width: 200
    },
    {
      title: '截仓时间',
      search: false,
      dataIndex: 'cutoffTime',
      width: 150
    },
    {
      title: '开船时间',
      search: false,
      dataIndex: 'shipTime',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      width: 100,
      fixed: 'right',
      render: (_, record: lineBatchTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          </Space>
        );
      }
    }
  ];

  useComponentDidMount(() => {
    fetchSettlementWeeksByYear({year: String(new Date().getFullYear())}).then(
      res => {
        setWeeks((res || [])?.reduce((p: any, v: string) => ({...p, [v]: v}), {})) 
      }
    )
  })

  return (
    <> 
      <ProTable
        bordered
        rowKey="id"
        options={false}
        columns={columns}
        search={{span: 6}}
        // toolBarRender={() => [
        //   <Button onClick={handleAdd} type="primary">
        //     <PlusOutlined />
        //     新建
        //   </Button>
        // ]}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          params.pageNum = params.current;
          const res = await fetchLpsLineBatchList({
            ...params,
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20,
          });
          return {
            data: res.data || [],
            total: res.total || 0,
            success: true
          }
        }}
        scroll={{x: calculateTableWidth(columns), y: 650}}
      />
      {visible && <LineBatchUpdate {...lineBatchProps} />}
    </>
  );
};


export default LineBatch;